package com.example.myone.Activity;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myone.Entity.User;
import com.example.myone.Fragment.LoginFragment;
import com.example.myone.Mapper.UserMapper;
import com.example.myone.Pager.MyPager;
import com.example.myone.R;
import com.example.myone.Util.ImageUtils;
import com.example.myone.Util.LoginInfoUtil;

import java.io.InputStream;

public class SettingActivity extends AppCompatActivity {

    private ImageView avatar;
    private TextView username;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_pager_setting);

        // 返回
        ImageView topBack = findViewById(R.id.top_back_button);
        topBack.setOnClickListener(v -> {
            finish();
        });
        // 标题
        TextView category = findViewById(R.id.top_title);
        category.setText("设置");
        // 修改用户名
        ImageView changeUsername = findViewById(R.id.changeUsername);
        changeUsername.setOnClickListener(v -> {
            showEditUsernameDialog();
        });
        // 获取用户数据并渲染
        username = findViewById(R.id.username);
        avatar = findViewById(R.id.avatar);
        User user = LoginInfoUtil.getUser(this);
        if (user != null) {
            ImageUtils.setImageByBase64Str(this, avatar, user.avatar);
            username.setText(user.username);
        }
        // 退出登录
        View logout = findViewById(R.id.logout_container);
        logout.setOnClickListener(v -> {
            // 点击按钮切换到 LoginFragment
            LoginInfoUtil.remove(this);
            MyPager.replaceFragment(new LoginFragment());
            finish();
        });

        // 上传图片
        avatar.setOnClickListener(v -> avatarImagePickerLauncher.launch("image/*"));
        // 上传图片
        RelativeLayout background = findViewById(R.id.my_background);
        background.setOnClickListener(v -> backgroundImagePickerLauncher.launch("image/*"));
    }

    private void showEditUsernameDialog() {
        // 使用 LayoutInflater 来加载对话框的布局
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.change_username_dialog, null);
        final EditText usernameEditText = dialogView.findViewById(R.id.changeUsername);
        // 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialogView);
        builder.setTitle("修改用户名")
                .setPositiveButton("确认", (dialog, which) -> {
                    String newUsername = usernameEditText.getText().toString().trim();
                    if (!newUsername.isEmpty()) {
                        username.setText(newUsername);
                        User user = LoginInfoUtil.getUser(this);
                        if (user != null) {
                            user.username = username.getText().toString();
                            UserMapper.updateUser(this, user);
                            LoginInfoUtil.remove(this);
                            LoginInfoUtil.save(this, user);
                            Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(this, "用户名不为空", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                .create()
                .show();
    }

    // 获取用户选择的头像图片
    private final ActivityResultLauncher<String> avatarImagePickerLauncher = registerForActivityResult(
            new ActivityResultContracts.GetContent(), result -> {
                if (result != null) {
                    try (
                            InputStream imageStream = getContentResolver().openInputStream(result);
                    ) {
                        Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                        avatar.setImageBitmap(selectedImage);
                        // 将Bitmap对象转换为Base64字符串
                        String base64Image = ImageUtils.convertBitmapToBase64(selectedImage);
                        User user = LoginInfoUtil.getUser(this);
                        if (user != null) {
                            user.avatar = base64Image;
                            UserMapper.updateUser(this, user);
                            LoginInfoUtil.remove(this);
                            LoginInfoUtil.save(this, user);
                            Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(this, "无法加载头像图片", Toast.LENGTH_SHORT).show();
                    }
                }
            });

    // 获取用户选择的背景图片
    private final ActivityResultLauncher<String> backgroundImagePickerLauncher = registerForActivityResult(
            new ActivityResultContracts.GetContent(), result -> {
                if (result != null) {
                    try {
                        InputStream imageStream = getContentResolver().openInputStream(result);
                        Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                        // 将Bitmap对象转换为Base64字符串
                        String base64Image = ImageUtils.convertBitmapToBase64(selectedImage);
                        User user = LoginInfoUtil.getUser(this);
                        if (user != null) {
                            user.background = base64Image;
                            UserMapper.updateUser(this, user);
                            LoginInfoUtil.remove(this);
                            LoginInfoUtil.save(this, user);
                            Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(this, "无法加载背景图片", Toast.LENGTH_SHORT).show();
                    }
                }
            });
}
